package poi.word;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
// TODO POI是否支持操作word 2003 以上版本
public class WordReader {
	private FileInputStream input;
	private WordExtractor extractor;
	private  String wordText;//word 内容
	public  String readWord(String wordDocPath){//wordDocPath,word文档的绝对路径
		try {
			input= new FileInputStream(new File(wordDocPath)); // 创建输入流读取Word文件
			extractor = new WordExtractor(input);// 创建WordExtractor
			wordText = extractor.getText();// 对Word文件进行提取
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try{
				if(input!=null){
					input.close();
				}
			}catch(IOException e){
				e.printStackTrace();
			}
		}
		return wordText;
	}
	public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
		String filePath = "D:\\software\\MyERP_Core\\myERP\\dsoframer";
		WordReader wr = new WordReader();
		String str = wr.readWord(filePath+"\\cj.doc");
		File file = new File(filePath+"\\cj_copy.doc");
		wr.writeWord("11", filePath+"\\cj2_copy.doc");
		System.out.println(str);
	}
	public void writeWord(String content,String filePath) throws FileNotFoundException, UnsupportedEncodingException{
	        byte b[] = content.getBytes("ISO-8859-1"); 
	        ByteArrayInputStream bais = new ByteArrayInputStream(b);   
	        FileOutputStream ostream = new FileOutputStream(filePath);   
	        
	        POIFSFileSystem fs = new POIFSFileSystem();  
	        try {
				fs.writeFilesystem(ostream);
				bais.close();   
		        ostream.close(); 
			} catch (IOException e) {
				e.printStackTrace();
			}   
	          
	}
}